package com.sayice.robotconflict.view.page

import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AddCircle
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.ColorPainter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.window.Dialog
import com.sayice.robotconflict.model.Message
import com.sayice.robotconflict.model.receive.FriendInfo
import com.sayice.robotconflict.model.receive.FriendReqEntity
import com.sayice.robotconflict.ui.screen.cdp
import com.sayice.robotconflict.util.unread
import com.sayice.robotconflict.util.vibrate
import com.sayice.robotconflict.view.route.Route
import com.sayice.robotconflict.viewmodel.GameViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * 好友管理页面
 *
 * @author shubing
 */
@Composable
fun Friends(viewModel: GameViewModel) {
    val scope = rememberCoroutineScope()
    val friendsState by viewModel.friendsFlow.collectAsState()
    val friendReqsState by viewModel.friendReqsFlow.collectAsState()
    var openFriendAddDialog by remember { mutableStateOf(false) }
    LaunchedEffect(Unit) {
        // 获取好友信息
        viewModel.sendToServer(Message(type = "social", action = "getFriends"))
        // 获取好友申请信息
        viewModel.sendToServer(Message(type = "social", action = "getFriendReqs"))
    }
    Box(modifier = Modifier.fillMaxSize()) {
        Button(modifier = Modifier.align(Alignment.TopStart), onClick = {
            viewModel.goToPage(Route.HALL)
        }) {
            Text("返回大厅")
        }
        Row(modifier = Modifier.fillMaxSize()) {
            // 好友列表
            Column(
                modifier = Modifier
                    .weight(1.0f)
                    .fillMaxHeight()
                    .padding(10.cdp)
            ) {
                Spacer(modifier = Modifier.weight(1.0f))
                Column(modifier = Modifier.weight(3.0f)) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text("好友")
                        IconButton(
                            onClick = { openFriendAddDialog = true },
                            modifier = Modifier.size(70.cdp)
                        ) {
                            Icon(
                                imageVector = Icons.Filled.AddCircle,
                                contentDescription = "添加好友按钮",
                                tint = Color.Blue
                            )
                        }
                    }
                    LazyColumn(
                        modifier = Modifier
                            .fillMaxSize()
                            .border(2.cdp, Color.Blue),
                        contentPadding = PaddingValues(10.cdp),
                        verticalArrangement = Arrangement.spacedBy(10.cdp)
                    ) {
                        items(friendsState) { friendInfo ->
                            var expanded by remember { mutableStateOf(false) }
                            val context = LocalContext.current
                            Friend(friendInfo = friendInfo, onLongClick = {
                                context.vibrate(longArrayOf(0, 40, 0, 0))
                                expanded = true
                            })
                            DropdownMenu(
                                expanded = expanded,
                                onDismissRequest = { expanded = false }) {
                                DropdownMenuItem(onClick = {
                                    scope.launch(Dispatchers.IO) {
                                        viewModel.sendToServer(
                                            Message(
                                                type = "social",
                                                action = "deleteFriend",
                                                data = friendInfo.id
                                            )
                                        )
                                        expanded = false
                                    }
                                }) {
                                    Text("删除")
                                }
                            }
                        }
                    }
                }
            }
            Spacer(modifier = Modifier.width(50.cdp))
            // 好友申请列表
            Column(
                modifier = Modifier
                    .weight(1.0f)
                    .fillMaxHeight()
                    .padding(10.cdp)
            ) {
                Spacer(modifier = Modifier.weight(1.0f))
                Column(modifier = Modifier.weight(3.0f)) {
                    Text(text = "好友申请")
                    LazyColumn(
                        modifier = Modifier
                            .fillMaxSize()
                            .border(2.cdp, Color.Blue),
                        contentPadding = PaddingValues(10.cdp),
                        verticalArrangement = Arrangement.spacedBy(10.cdp)
                    ) {
                        items(friendReqsState) {
                            FriendReq(it, onClick = {
                                scope.launch(Dispatchers.IO) {
                                    viewModel.sendToServer(
                                        Message(
                                            type = "social",
                                            action = "readFriendReq",
                                            data = it.from.id
                                        )
                                    )
                                }
                            }, onReply = { agree ->
                                scope.launch(Dispatchers.IO) {
                                    viewModel.sendToServer(
                                        Message(
                                            type = "social",
                                            action = if (agree) "agreeFriendReq" else "ignoreFriendReq",
                                            data = it.from.id
                                        )
                                    )
                                }
                            })
                        }
                    }
                }
            }
        }
        if (openFriendAddDialog) {
            // 添加好友弹框
            FriendAddDialog(
                viewModel = viewModel,
                onDismissRequest = { openFriendAddDialog = false }
            )
        }
    }
}

/**
 * 弹框-添加好友
 */
@Composable
private fun FriendAddDialog(viewModel: GameViewModel, onDismissRequest: () -> Unit) {
    val scope = rememberCoroutineScope()
    val searchedPlayersState by viewModel.searchedPlayersFlow.collectAsState()
    var name by remember { mutableStateOf("") }
    var clickedPlayer by remember { mutableStateOf<FriendInfo?>(null) }
    Dialog(onDismissRequest = {
        onDismissRequest()
        viewModel.clearSearchedPlayers()
    }) {
        Column(
            modifier = Modifier
                .size(width = 1800.cdp, height = 1000.cdp)
                .background(Color.White)
                .padding(10.cdp), horizontalAlignment = Alignment.CenterHorizontally
        ) {
            TextField(value = name, onValueChange = {
                name = it
                scope.launch(Dispatchers.IO) {
                    viewModel.sendToServer(
                        Message(type = "social", action = "findPlayers", data = it)
                    )
                }
            })
            Spacer(modifier = Modifier.height(50.cdp))
            LazyColumn(
                modifier = Modifier.fillMaxSize(),
                contentPadding = PaddingValues(10.cdp),
                verticalArrangement = Arrangement.spacedBy(10.cdp)
            ) {
                items(searchedPlayersState) { player ->
                    Friend(friendInfo = player, onClick = {
                        clickedPlayer = player
                    })
                }
            }
            if (clickedPlayer != null) {
                val theClickedPlayer = clickedPlayer!!
                // 确认框
                AlertDialog(
                    onDismissRequest = { clickedPlayer = null },
                    title = { Text("添加${theClickedPlayer.name}为好友？") },
                    confirmButton = {
                        TextButton(onClick = {
                            scope.launch(Dispatchers.IO) {
                                viewModel.sendToServer(
                                    Message(
                                        type = "social",
                                        action = "sendFriendReq",
                                        data = theClickedPlayer.id
                                    )
                                )
                                clickedPlayer = null
                            }
                        }) {
                            Text("确认")
                        }
                    },
                    dismissButton = {
                        TextButton(onClick = {
                            clickedPlayer = null
                        }) {
                            Text("取消")
                        }
                    }
                )
            }
        }
    }
}

/**
 * 好友
 */
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun Friend(
    friendInfo: FriendInfo,
    onClick: () -> Unit = {},
    onLongClick: (() -> Unit)? = null
) {
    Row(
        modifier = Modifier.combinedClickable(onClick = onClick, onLongClick = onLongClick),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Image(
            painter = ColorPainter(Color.Blue), contentDescription = null,
            modifier = Modifier
                .clip(CircleShape)
                .size(80.cdp),
            alpha = if (friendInfo.online) 1.0f else 0.5f
        )
        Spacer(modifier = Modifier.width(50.cdp))
        Text(friendInfo.name)
    }
}

/**
 * 好友申请
 */
@Composable
private fun FriendReq(
    friendReqEntity: FriendReqEntity,
    onClick: () -> Unit,
    onReply: (agree: Boolean) -> Unit
) {
    Row(
        modifier = Modifier
            .unread(!friendReqEntity.read)
            .clickable { onClick() },
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = friendReqEntity.from.name,
            modifier = Modifier.width(200.cdp),
            overflow = TextOverflow.Ellipsis
        )
        Text("请求添加为好友")
        Spacer(modifier = Modifier.width(50.cdp))
        Button(onClick = { onReply(true) }) {
            Text("同意")
        }
        Spacer(modifier = Modifier.width(25.cdp))
        Button(onClick = { onReply(false) }) {
            Text("忽略")
        }
    }
}